package cn.netuo.bumbersoll;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.WindowManager;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rooten.help.apploop.loopentity.TaskItem;
import com.rooten.util.Util;

import java.io.File;
import java.util.Date;

import cn.netuo.bumbersoll.entity.Action;
import cn.netuo.bumbersoll.entity.MqttFromS;
import cn.netuo.bumbersoll.helper.LocateHelper;
import cn.netuo.bumbersoll.helper.MqttFromCHelper;
import cn.netuo.bumbersoll.helper.ble.BLEHelper;
import cn.netuo.bumbersoll.helper.screen.ScreenHelper;
import cn.netuo.bumbersoll.interf.OnBlueToothConnectListener;
import cn.netuo.bumbersoll.mqtt.IGetMessageCallBack;
import cn.netuo.bumbersoll.mqtt.MQTTService;
import cn.netuo.bumbersoll.mqtt.MyServiceConnection;
import cn.netuo.bumbersoll.upgrade.Version;
import cn.netuo.bumbersoll.util.BatteryHelper;
import cn.netuo.bumbersoll.util.BsUtil;
import lib.grasp.helper.DownLoadHelper;
import lib.grasp.mvp.BaseMvpActivity;
import lib.grasp.mvp.BaseMvpPresenter;
import lib.grasp.util.AppUtil;
import lib.grasp.util.FileUtil;
import lib.grasp.util.L;
import lib.grasp.util.NetUtil;
import lib.grasp.util.PathUtil;
import lib.grasp.util.PermissionUtil;
import lib.grasp.util.TOAST;
import lib.grasp.widget.MessageBoxGrasp;

import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;

/**
 * 横竖屏切换时,并不会每次都生成一个Presenter
 */
public class MainPtr extends BaseMvpPresenter implements OnBlueToothConnectListener, IGetMessageCallBack, AMapLocationListener {

    /** wm */
    public WindowManager        mWindowManager;
    public BLEHelper            mBleHelper;

    /** MQTT连接器 */
    public MyServiceConnection  mServiceConnection;

    /** 定位帮助类 */
    public LocateHelper         mLocateHelper;

    public ScreenHelper         mScreenHelper;

    MainPtr(@NonNull BaseMvpActivity view) {
        super(view);
    }

    @Override
    protected MainActivity getView() {
        if (mViewRef == null) return null;
        return (MainActivity) mViewRef;
    }

    void init(){
        initConstant();

        initBleService();
        initMqttService();
        initLoop();
        doBindMqttService();
        initLocate();
        initScreen();
        registerReceiver();
        startDownload();
        BsUtil.resetLowPowerMode(getView());
        doStartPlay();
    }


    /** 初始化mqtt订阅主题,设备ID(从DB里面获取) */
    private void initConstant(){
        BizConstant.ARG_MQTT_TOPIC = App.getApp().getTableMgr().getTbArg().queryByArgName(BizConstant.ARG_MQTT_TOPIC_KEY);
        mWindowManager = ((WindowManager) getView().getApplicationContext().getSystemService(Context.WINDOW_SERVICE));                                                     // 赋值到内存
    }

    /** 初始化BLE服务(0: 常开(默认); 1:不常开(用完就关)) */
    void initBleService() {
        String isBtKeepOnStr = App.getApp().getTableMgr().getTbArg().queryByArgName(BizConstant.ARG_IS_BT_KEPP_ON_KEY);
        BizConstant.IS_BT_KEPP_ON = !TextUtils.equals(isBtKeepOnStr, "1");

        mBleHelper = new BLEHelper(getView());
        App.getApp().setBLEHelper(mBleHelper);
        App.getApp().getBLEHelper().setListener(this);
    }


    /** 初始化mqtt服务 */
    private void initMqttService() {
        if(mServiceConnection != null) return;
        mServiceConnection = new MyServiceConnection();
        mServiceConnection.setIGetMessageCallBack(this);
    }

    /** 开启轮询(心跳, 热更新, 广告) */
    private void initLoop(){
        TaskItem backToFront = new TaskItem(BizConstant.BROAD_HEARTBEAT, BizConstant.INTERVAL_HEARTBEATS, 0);
        App.getApp().startAppOnService(backToFront);
    }

    /** 绑定MQTT服务 */
    private void doBindMqttService(){
        Intent intent1 = new Intent(getView(), MQTTService.class);
        getView().bindService(intent1, mServiceConnection, Context.BIND_AUTO_CREATE);
    }


    /** 初始化定位帮助类 */
    private void initLocate(){
        mLocateHelper = new LocateHelper(getView(), this);
        startLocate();
    }


    /** 初始化定位帮助类 */
    private void initScreen(){
        mScreenHelper = ScreenHelper.getInstance(getView());
    }


    /** 注册广播监听(主要监听蓝牙的一些事情) */
    private void registerReceiver(){
        App.getApp().getLocalBroadMgr().registerReceiver(mBroadcastReceiver, getIntentFilter());// 注册广播
        getView().registerReceiver(App.getApp().getBatteryReceiver(), BatteryHelper.getIntentFilter());// 注册广播
    }

    /** 开始下载任务 */
    private void startDownload(){
        App.getApp().mDownLoadId = App.getApp().getFileDownloadMgr().registerCategory("下载视频",  1);
        App.getApp().getFileDownloadMgr().startDownload();
    }


    /** 亮屏&开始播放 */
    private void doStartPlay(){
        if(mScreenHelper != null) mScreenHelper.screenOn();
        getView().doStartPlay();
    }

    /** 停止播放&灭屏 */
    private void doStopPlay(){
        getView().doStopPlay();
        App.getApp().getBLEHelper().addAction(BsUtil.getTestCmd(getView(), BizConstant.REQUEST_NAME_LIGHT_OFF));
        if(mScreenHelper != null) mScreenHelper.screenOff();
    }

    /** 请求开始定位 */
    private void startLocate(){
        if(mLocateHelper != null) mLocateHelper.startLocation();
    }


    /** 获取蓝牙动态广播的监听 */
    private IntentFilter getIntentFilter() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BizConstant.BROAD_LOCATE);
        intentFilter.addAction(BizConstant.BROAD_BIZ_HEARTBEAT);
        intentFilter.addAction(BizConstant.BROAD_MQTT_STATE);
        intentFilter.addAction(BizConstant.BROAD_VIDEO_TASK);
        intentFilter.addAction(BizConstant.BROAD_LOW_POWER_CHANGED);
        return intentFilter;
    }


    /** 蓝牙指令发送完成 */
    @Override
    public void onOrderFinish(MqttFromS<Action> mqttFromS) {
        if(mqttFromS == null) return;
        if(mqttFromS.data == null || mqttFromS.data.cmd == null) return;

        // 非自动执行关机指令// mqtt到服务器,  发送回执
        if(!TextUtils.equals(mqttFromS.cmd, BizConstant.CMD_TYPE_ACT_AUTO))
            MqttFromCHelper.doSendReceipt(getView(), mqttFromS, getView().isPlaying(), App.getApp().getVideos());

        // 如果是开电的指令, 我们要存入DB, 以便自己轮询中判断按时断电
        // 如果是开电指令完成, 存入DB(待会要关电)
        if(TextUtils.equals(mqttFromS.data.requestName, BizConstant.REQUEST_NAME_USB_POWERON)) {
            L.logOnly("开电指令执行成功, 将[定时]关电");
            mBleHelper.setOffUsbAction(mqttFromS);
        }

        // 如果是自动关电指令完成, 置空
        else if(TextUtils.equals(mqttFromS.data.requestName, BizConstant.REQUEST_NAME_AUTO_POWEROFF) || TextUtils.equals(mqttFromS.cmd, BizConstant.CMD_TYPE_ACT_AUTO)){
            L.logOnly("[定时]关电指令执行成功, 将置空");
            mBleHelper.setOffUsbAction(null);
        }
    }


    /** 收到MQTT消息 */
    @Override
    public void onNewMessage(String message) {
        MqttFromS mqttFromS = null;
        try{ mqttFromS = new Gson().fromJson(message, new TypeToken<MqttFromS>() {}.getType()); }
        catch (Exception e){ L.logOnly("服务器数据出错"); }
        if(mqttFromS == null) return;

        switch (mqttFromS.cmd){
            case BizConstant.CMD_TYPE_AD: {         // 广告视频
                L.logOnly("收到广告视频");
                MqttFromCHelper.doSendReceipt(getView(), mqttFromS, getView().isPlaying(), App.getApp().getVideos());
//                if(BizConstant.IS_NOW_IN_LOWPOWER_MODE) return; // 如果当前正在低电模式, 则不下载广告
                BsUtil.doOnNewVideoAdTask(message);
                break;
            }

            case BizConstant.CMD_TYPE_ACT: {        // 命令
                L.logOnly("收到命令");
                BsUtil.addActionFromMsg(message);
                break;
            }

            case BizConstant.CMD_TYPE_REBOOT: {     // 请求重启APP
                L.logOnly("收到重启请求");
                MqttFromCHelper.doSendReceipt(getView(), mqttFromS, getView().isPlaying(), App.getApp().getVideos());
                getView().getView().postDelayed(BsUtil::stopApp, 1000);
                break;
            }

            case BizConstant.CMD_TYPE_RESETCMD: {     // 请求重置命令
                L.logOnly("收到重置命令请求");
                try {
                    BsUtil.addOrRefreshCmd(message);
                    MqttFromCHelper.doSendReceipt(getView(), mqttFromS, getView().isPlaying(), App.getApp().getVideos());
                } catch (Exception e) {
                    L.logOnly("服务器数据出错");
                }
                break;
            }

            case BizConstant.CMD_TYPE_REQUEST_HEARTBEAT:{
                L.logOnly("收到心跳请求");
                if(getView().getIjkVideoView() != null) MqttFromCHelper.sendHeartBeat(getView(), getView().isPlaying(), App.getApp().getVideos());
                MqttFromCHelper.doSendReceipt(getView(), mqttFromS, getView().isPlaying(), App.getApp().getVideos());
                break;
            }

            case BizConstant.CMD_TYPE_UNBIND:{
                L.logOnly("收到解绑请求");
                SettingActivity.doUnbind(getView(), false);
                MqttFromCHelper.doSendReceipt(getView(), mqttFromS, getView().isPlaying(), App.getApp().getVideos());
                break;
            }

            case BizConstant.CMD_TYPE_VOL:{
                L.logOnly("收到音量调节请求");
                int targetVol = BsUtil.parseNewVolTask(message);
                if(targetVol < 0) break;
                BsUtil.setMediaVolRate(getView(), targetVol);
                MqttFromCHelper.doSendReceipt(getView(), mqttFromS, getView().isPlaying(), App.getApp().getVideos());
                break;
            }

            case BizConstant.CMD_TYPE_VERSION:{
                L.logOnly("(强制)目标版本");
                MqttFromCHelper.doSendReceipt(getView(), mqttFromS, getView().isPlaying(), App.getApp().getVideos());
                if(TextUtils.isEmpty(message)) break;
                Version version = BsUtil.parseNewVersion(message);
                if(version == null) break;
                doOnNewVersion(version);
                break;
            }
        }
    }

    private void doOnNewVersion(Version version){
        if(getView() == null || version == null) return;
        TOAST.showShort(getView(), "发现新版本" + version.versionName + ",自动下载安装!");

        Bundle bundle = new Bundle();
        bundle.putString("fileName",        "tys");
        bundle.putString("versionName",     version.versionName);
        bundle.putLong("size",              version.size);
        bundle.putString("downloadPath",    version.downloadPath);

        // 版本升级
        Intent intent = new Intent();
        intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
        intent.putExtras(bundle);
        intent.putExtra("isSilenceInstall", true);
        doUpGrade(getView(), intent);
    }

    @Override
    public void onConnStateChanged(boolean isConned) {
        if(getView() == null) return;
        getView().onConnStateChanged(isConned);
    }

    /** 定位回调 */
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if(aMapLocation == null) return;
        double lat = aMapLocation.getLatitude();
        double lng = aMapLocation.getLongitude();
        L.logOnly("LAT:" + lat);
        L.logOnly("LNG:" + lng);
        if(lat == 0 || lng == 0) return;
        BizConstant.LOCATE_LAT = aMapLocation.getLatitude();
        BizConstant.LOCATE_LNG = aMapLocation.getLongitude();
        BsUtil.saveLastLoadDate(getView(), BizConstant.ARG_REFRESH_LOCATE_DAY, System.currentTimeMillis());
    }


    /** 蓝牙事件广播(本人蓝牙服务发出的广播) */
    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context arg0, Intent intent) {
            String action = intent.getAction();
            assert action != null;
            switch (action){
                case BizConstant.BROAD_LOCATE: {            // 请求定位
                    if(BsUtil.checkLastLoadDate(getView(), BizConstant.ARG_REFRESH_LOCATE_DAY, new Date().getTime())) return;
                    L.logOnly("请求定位");
                    startLocate();
                    break;
                }
                case BizConstant.BROAD_BIZ_HEARTBEAT: {            // 发个心跳
                    if(getView().getIjkVideoView() != null) MqttFromCHelper.sendHeartBeat(getView(), getView().isPlaying(), App.getApp().getVideos());
                    // 检测下gprs有没有开启(没有开就开了)
                    if(!NetUtil.getMobileDataState(getView(), null)) NetUtil.setGprsEnabled_Android5(getView(), true);
                    L.logOnly("发个业务心跳");
                    break;
                }
                case BizConstant.BROAD_MQTT_STATE: {        // 检查MQTT连接状态
                    if(mScreenHelper != null ){
                        if(!BizConstant.IS_NOW_IN_LOWPOWER_MODE) doStartPlay();  // 防止在播放时被人点了黑屏
                        else doStopPlay();
                    }

                    if(mServiceConnection == null || mServiceConnection.getMqttService() == null) return;
                    mServiceConnection.getMqttService().doClientConnection();
                    break;
                }
                case BizConstant.BROAD_LOW_POWER_CHANGED: {   // 进入/退出低电模式
                    if(!BizConstant.IS_NOW_IN_LOWPOWER_MODE){
                        doStartPlay();
                        return;
                    }
                    doStopPlay();
                    break;
                }
                case BizConstant.BROAD_VIDEO_TASK: {        // 检查广告视频下载任务
                    getView().getIjkVideoView().doCheckVideoTask();
                    break;
                }
            }
        }
    };

    void onDestroy() {
        if(mServiceConnection != null)  getView().unbindService(mServiceConnection);
        App.getApp().getLocalBroadMgr().unRegisterReceiver(mBroadcastReceiver);
        getView().unregisterReceiver(App.getApp().getBatteryReceiver());
        if(mLocateHelper != null)  mLocateHelper.onDestroy();
        if(BizConstant.IS_BT_KEPP_ON){                      //  平时不关蓝牙,最后关
            App.getApp().getBLEHelper().disConnect();
            App.getApp().getBLEHelper().onDestroy();
        }
        App.getApp().getFileDownloadMgr().stopDownload();
    }

    /**
     * 版本升级
     */
    public void doUpGrade(Context ctx, Intent intent) {
        if (!(ctx instanceof Activity)) return;
        if (!PermissionUtil.checkDangerousPermission((Activity) ctx, Manifest.permission.CAMERA)) return;
        boolean isSilenceInstall = Util.getBoolean(intent, "isSilenceInstall", true);

        Version version         = new Version();
        version.fileName        = Util.getString(intent, "fileName");
        version.versionName     = Util.getString(intent, "versionName");
        version.size            = Util.getLong(intent, "size");
        version.downloadPath    = Util.getString(intent, "downloadPath");

        File tempFile = new File(PathUtil.getApkAbsPath(version.fileName, false, version.versionName));
        File saveFile = new File(PathUtil.getApkAbsPath(version.fileName, true, version.versionName));
        if (FileUtil.isFileExists(saveFile.getAbsolutePath())) {
            if (saveFile.length() != version.size) {
                FileUtil.delFile(saveFile); // 删掉之后重新下载
            } else {
                doInstall(ctx, isSilenceInstall, saveFile);
                return;
            }
        }

        FileUtil.delDir(tempFile);
        FileUtil.delDir(saveFile);

        DownLoadHelper loadHelper = new DownLoadHelper(ctx, version.downloadPath, saveFile.getAbsolutePath());
        loadHelper.setLoadListener(new lib.grasp.helper.LoadListener() {
            @Override
            public void onSuccess() {
                doInstall(ctx, isSilenceInstall, saveFile);
            }

            @Override
            public void onFail() {
                MessageBoxGrasp.infoMsg(ctx, "下载失败, 请稍候再试");
                getView().finish();
            }
        });
        loadHelper.startLoad();
    }

    private void doInstall(Context ctx, boolean isSilenceInstall, File saveFile){
        L.logOnly("isSilenceInstall:" + isSilenceInstall);
        L.logOnly("AppUtil.isRoot():" + AppUtil.isRoot());
        if(isSilenceInstall && AppUtil.isRoot()){   // 如果已经root并且要静默安装
            if (TextUtils.isEmpty(saveFile.getAbsolutePath())) return;
            AppUtil.installSilence(ctx, saveFile.getAbsolutePath());
        }
        else{
            if (TextUtils.isEmpty(saveFile.getAbsolutePath())) return;
            AppUtil.installAPK(ctx, saveFile.getAbsolutePath(), getView().getPackageName() + ".fileprovider");
            getView().finish();

//            MessageBoxGrasp.confirmMsg(ctx, "确认提示框", "下载完成,现在安装?",
//                    v -> {
//                        if (TextUtils.isEmpty(saveFile.getAbsolutePath())) return;
//                        AppUtil.installAPK(ctx, saveFile.getAbsolutePath(), getView().getPackageName() + ".fileprovider");
//                        getView().finish();
//                    },
//                    v -> getView().finish(),
//                    true);
        }
    }
}
